//
//  UIViewController+XXExtension.m
//  SHWheel
//
//  Created by YYKJ on 2020/11/6.
//  Copyright © 2020 YYKJ. All rights reserved.
//

#import "UIViewController+XXExtension.h"
#import "UIView+XXExtension.h"
#import "SHUIHelper.h"

@implementation UIViewController (XXExtension)

- (UIViewController *)xx_visibleViewController {
    if (self.presentedViewController) {
        return [self.presentedViewController xx_visibleViewController];
    }
    
    if ([self isKindOfClass:[UINavigationController class]]) {
        return [((UINavigationController *)self).visibleViewController xx_visibleViewController];
    }
    
    if ([self isKindOfClass:[UITabBarController class]]) {
        return [((UITabBarController *)self).selectedViewController xx_visibleViewController];
    }
    
    if ([self xx_isViewLoadedAndVisible]) {
        return self;
    } else {
        return nil;
    }
}

- (BOOL)xx_isViewLoadedAndVisible {
    return self.isViewLoaded && self.view.xx_visible;
}

@end


@implementation SHUIHelper (ViewController)

+ (UIViewController *)visibleViewController {
    UIViewController *rootViewController = UIApplication.sharedApplication.delegate.window.rootViewController;
    UIViewController *visibleViewController = [rootViewController xx_visibleViewController];
    return visibleViewController;
}

@end
